<template>
  <Headerbar />
  <div class="forum-create">
    <div class="left">
      <n-h2 prefix="bar"> {{ props.id == 0 ? '创建' : '修改' }}你的求助 </n-h2>
      <n-card class="card">
        <n-popover placement="bottom" v-model:show="picListShow">
          <template #trigger>
            <div
              v-if="!questionData.image"
              style="height: 8vh; margin-top: 20px; cursor: pointer"
            >
              <n-empty size="small">悬浮/点击以选择封面 </n-empty>
            </div>
            <img v-else :src="questionData.image" alt="封面" class="cover" />
          </template>
          <!-- 照片墙 -->
          <div>
            <n-grid :x-gap="12" :y-gap="8" :cols="3">
              <n-grid-item v-for="(pic, index) in picList" :key="index">
                <img
                  :src="pic.url"
                  :alt="pic.name"
                  class="pic-card"
                  @click="chooseCover(index)"
                />
              </n-grid-item>
              <!-- <n-grid-item>
                <n-upload
                  action="https://www.mocky.io/v2/5e4bafc63100007100d8b70f"
                  :default-file-list="defaultPicList"
                  list-type="image-card"
                  :show-preview-button="false"
                />
              </n-grid-item> -->
            </n-grid>
          </div>
        </n-popover>
        <div class="head">
          <!-- 标题 -->
          <div class="title">
            <span class="desc">标题</span><br />
            <span class="sub-desc">问题要以问号结尾哦</span>
            <n-input
              v-model:value="questionData.title"
              type="text"
              placeholder=".e.g 求 “xxx” 的pdf全文，感谢！"
              :maxlength="50"
              show-count
            ></n-input>
          </div>
        </div>
        <!-- 求助内容 -->
        <div class="content">
          <span class="desc">详情描述</span><br />
          <span class="sub-desc"
            >包括所有你需要求助的信息，请尽可能的详细，以便他人能更好地帮助到你
          </span>
          <n-input
            type="textarea"
            v-model:value="questionData.content"
            clearable
            show-count
            :maxlength="200"
            placeholder=""
          >
          </n-input>
        </div>
        <!-- 选择关联文章 -->
        <!-- <div class="content">
          <span class="desc">问题关联</span><br />
          <span class="sub-desc"
            >在这里你可以选择或输入问题相关的学者、学术作品（输入'@'以匹配用户；输入'#'以匹配文章；以英文分号自动分隔）</span
          >
          <n-mention
            v-model:value="questionData.mentions"
            placeholder="请输入以英文分号分隔的关联学者、学术作品id"
            :prefix="['@', '#']"
            separator=";"
            @search="searchRecent"
            :loading="loading"
            :options="mentionList"
          /> -->
        <!-- <n-mention
            v-model:value="questionData.mentions"
            :options="mentionList"
            :prefix="['@', '#']"
            @search="searchRecent"
            :loading="loading"
            separator=";"
          /> -->
        <!-- </div> -->
        <!-- 关联 -->
        <div class="content">
          <span class="desc">关联学术成果</span><br />
          <span class="sub-desc">输入学术成果的ID</span>
          <n-space>
            <n-dynamic-tags
              v-model:value="questionData.mentions"
              :max="3"
              :render-tag="renderTag"
            >
              <template #trigger="{ activate, disabled }">
                <n-button
                  size="small"
                  @click="activate()"
                  type="primary"
                  dashed
                  :disabled="disabled"
                >
                  <template #icon>
                    <n-icon>
                      <Add />
                    </n-icon>
                  </template>
                  添加
                </n-button>
              </template>
            </n-dynamic-tags>
          </n-space>
        </div>
        <!-- 标签 -->
        <div class="content">
          <span class="desc">分类标签</span><br />
          <span class="sub-desc">选择求助的所属标签</span>
          <n-space>
            <n-tag
              v-for="tag in tags"
              :key="tag.name + tag.checked"
              checkable
              v-model:checked="tag.checked"
              :style="{
                border: tag.checked ? '' : '1px dashed #999'
              }"
            >
              {{ tag.name }}
            </n-tag>
            <n-dynamic-tags v-model:value="extraTags" :max="3" type="primary">
              <template #trigger="{ activate, disabled }">
                <n-button
                  size="small"
                  @click="activate()"
                  type="primary"
                  dashed
                  :disabled="disabled"
                >
                  <template #icon>
                    <n-icon>
                      <Add />
                    </n-icon>
                  </template>
                  添加
                </n-button>
              </template>
            </n-dynamic-tags>
          </n-space>
        </div>
        <!-- 按钮 -->
        <n-space justify="space-around" style="padding: 20px 4% 0">
          <n-popconfirm @positive-click="$router.go(-1)">
            <template #trigger>
              <n-button style="width: 350px" secondary> 返回 </n-button>
            </template>
            您确定要返回吗，你当前修改的信息将不会被保存
          </n-popconfirm>
          <n-button style="width: 350px" type="primary" @click="submit">{{
            props.id == 0 ? '提 交' : '修 改'
          }}</n-button>
        </n-space>
      </n-card>
    </div>
    <div class="right">
      <info-card class="card" :id="id"></info-card>
    </div>
  </div>
  <img
    src="@/assets/bg/cheese-02.png"
    class="fixed right-0 bottom-0 -z-10 w-[466px] h-[285px]"
  />
</template>

<script setup lang="jsx">
import InfoCard from './components/InfoCard.vue'
import { EyeOutline, Add } from '@vicons/ionicons5'
import { useNotification } from 'naive-ui'
// import useMention from '@/utils/mention'
import api from '@/api/api'
const { Help, Message } = api
// const { convertString2TwoLists } = useMention()
const id = localStorage.getItem('id')
const message = useMessage()
const router = useRouter()
const route = useRoute()
const notification = useNotification()

const hasModal = ref(true)

const props = defineProps({
  id: String
})

const renderTag = (tag, index) => {
  return (
    <n-tag
      type="primary"
      onClick={() => {
        window.open('/research/detail/' + tag)
      }}
      style={{ cursor: 'pointer' }}
    >
      {tag}
    </n-tag>
  )
}

onMounted(() => {
  if (props.id != 0) {
    Help.getDetail({
      id: props.id
    }).then((res) => {
      if (res.success) {
        questionData.value = res.data
        if (res.data.mentions)
          questionData.value.mentions = res.data.mentions.map((item) => item.id)
        // if (store.state.auth) {
        if (questionData.value.authorId !== localStorage.getItem('id')) {
          router.push('forum/list/0')
          message.error('没有权限')
        }
        // } else {
        //   router.push('forum/list/0')
        //   message.error('没有权限')
        // }
        getTags()
      } else {
        message.error('错误访问')
        router.go(-1)
      }
    })
  }
  console.log('query', route.query)
  if (route.query.mention) {
    // if (questionData.value.mentions) {
    //   // may occur bug
    //   questionData.value.mentions
    // } else {
    //   questionData.value.mentions = '#' + route.query.mention + ';'
    // }
    questionData.value.mentions.push(route.query.mention)
  }
})

const getTags = () => {
  questionData.value.tags.forEach((t) => {
    t = t.trim()
    let flag = false
    tags.value.forEach((tt) => {
      if (tt.name === t) {
        tt = { ...tt, checked: true }
        flag = true
      }
    })
    if (!flag) {
      extraTags.value.push(t)
    }
  })
}

// 是否显示picList
const picListShow = ref(false)
const picList = ref([
  {
    name: 'guowang1',
    url: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwx4.sinaimg.cn%2Flarge%2F0022GRovly1gvpgv5kzf3j60np0dc3zp02.jpg&refer=http%3A%2F%2Fwx4.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1639009705&t=dba70cb61d7f1dd30faa5d33669eccfd'
  },
  {
    name: 'genshin',
    url: 'https://upload-bbs.mihoyo.com/upload/2022/09/09/18643246/e6b3ebb9cb17eb62843403dfcc877869_7342710252343673823.jpg?x-oss-process=image/resize,s_600/quality,q_80/auto-orient,0/interlace,1/format,jpg'
  },
  {
    name: 'guowang3',
    url: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fww1.sinaimg.cn%2Fmw690%2F9c7e9b15gy1gw49nhppclj21hc0u07ce.jpg&refer=http%3A%2F%2Fwww.sina.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1639903338&t=7f4e244fa377aef2bc516f749f3be32e'
  },
  {
    name: 'jojo',
    url: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fqqpublic.qpic.cn%2Fqq_public%2F0%2F0-3142600724-B6FF0A5094E58A91D249BA6DE28CF1A4%2F0%3Ffmt%3Djpg%26size%3D189%26h%3D450%26w%3D900%26ppv%3D1.jpg&refer=http%3A%2F%2Fqqpublic.qpic.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1639903403&t=a090b0927271716a0f578cac62f8a1fe'
  },
  {
    name: 'guowang4',
    url: 'https://img2.baidu.com/it/u=3464766295,309940146&fm=253&fmt=auto&app=120&f=JPEG?w=690&h=388'
  },
  {
    name: 'dinghui',
    url: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic2.zhimg.com%2Fv2-7a2d5fcb06c1931ca882f9eeba6d9ed0_1200x500.jpg&refer=http%3A%2F%2Fpic2.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1639903618&t=f6d643ed3bb6c9dad9198cce88a8c28f'
  }
])
// 选择封面
const chooseCover = (index) => {
  questionData.value.image = picList.value[index].url
  picListShow.value = false
}

// 提交
const submit = () => {
  Help.saveHelp({
    id: props.id,
    ...questionData.value
  }).then((res) => {
    if (res.success) {
      message.success('提交成功')
      router.push('/forum/detail/' + res.data.id)
    } else {
      message.info('创建失败')
    }
  })
}

// 求助的信息
const questionData = ref({
  title: '',
  content: '',
  image: '',
  mentions: [],
  tags: [],
  authorId: 0
})
const extraTags = ref([])

//标签
const tags = ref([
  {
    name: '问答',
    checked: false
  },
  {
    name: '求文献',
    checked: false
  },
  {
    name: '项目',
    checked: false
  }
])
const getNewTags = () => {
  questionData.value.tags = []
  tags.value.forEach((t) => {
    if (t.checked) {
      if (questionData.value.tags.indexOf(t.name) == -1) {
        questionData.value.tags.push(t.name.trim())
      }
    } else {
      let index = questionData.value.tags.indexOf(t.name)
      if (index !== -1) {
        questionData.value.tags.splice(index, 1)
      }
    }
  })
  extraTags.value.forEach((t) => {
    t = t.trim()
    if (questionData.value.tags.indexOf(t) == -1) {
      questionData.value.tags.push(t)
    }
  })
}
watch(
  [
    tags,
    () => {
      return extraTags.value
    }
  ],
  () => {
    getNewTags()
  },
  {
    deep: true
  }
)

const loading = ref(false)
const mentionList = ref([])
let searchTimerId = null
const searchRecent = (pattern, prefix) => {
  // pattern is the text after the prefix
  if (searchTimerId !== null) clearTimeout(searchTimerId)
  loading.value = true
  if (prefix === '@') {
    searchTimerId = setTimeout(() => {
      Message.getContact()
        .then((res) => {
          if (res.success) {
            mentionList.value = res.list.map((item) => {
              return {
                label: item.name,
                value: item.uid
              }
            })
          }
          loading.value = false
        })
        .catch(() => {
          loading.value = false
        })
    }, 1000)
  } else {
    // TODO fake
    searchTimerId = setTimeout(() => {
      mentionList.value = [
        { label: pattern + '成果', value: 1 },
        {
          label: pattern + '论文',
          value: 2
        },
        {
          label: pattern + '项目',
          value: 3
        }
      ]
      loading.value = false
    }, 1000)
  }
}
</script>

<style scoped lang="scss">
.pic-card {
  cursor: pointer;
  height: 3em;
  width: 6em;
  object-fit: cover;
  background-color: #eee;
}
.modal {
  background: rgba(0, 0, 0, 0.4);
}
.forum-create {
  display: flex;
  justify-content: center;
  padding: 6vh 5vw 0;
  .left {
    width: 60vw;
    margin: 0 2vw;
  }

  .right {
    position: -webkit-sticky; /* Safari */
    position: sticky;
    top: 5vh;
    width: 30vw;
    height: 20vh;
  }
}

.avatar {
  width: 35px;
  height: 35px;
}

.card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08), 0 1px 2px rgba(0, 0, 0, 0.1);
  border-radius: 10px;
  margin-bottom: 30px;
  padding-bottom: 20px;
}

:deep(.n-card) > .n-card__content:first-child,
.n-card > .n-card__footer:first-child {
  padding: 0;
}

.head {
  padding: 30px 30px 0px;
  width: 100%;
  box-sizing: border-box;
  overflow: hidden;
}
.desc {
  font-size: 1rem;
  font-weight: 600;
}
.sub-desc {
  font-size: 12px;
}

.username {
  color: #4480c9;
  cursor: pointer;
  margin: 0 20px 0 10px;
}

.date {
  font-size: 13px;
  color: rgb(136, 136, 136);
  position: relative;
  flex: 1;
}

.options {
  position: absolute;
  right: 0;
  top: 0px;
  cursor: pointer;
  font-size: 14px;
  user-select: none;
  display: flex;
  .divider {
    margin: 0 10px;
    color: #ccc;
  }
}

.content {
  margin-top: 18px;
  line-height: 23px;
  word-break: break-all;
  padding: 0 30px;
  box-sizing: border-box;
}
.cover {
  width: 100%;
  height: 18em;
  object-fit: cover;
  cursor: pointer;
}
.like {
  height: 8vh;
  line-height: 8vh;
  text-align: center;
}
@media screen and (max-width: 992px) {
  .forum-create {
    padding: 0;
    padding-top: 10px;
  }
  .right {
    display: none;
  }
  .left {
    width: 100vw !important;
    .card {
      margin-bottom: 0;
      box-shadow: none;
      border: none;
      border-radius: 0;
      .head,
      .content {
        padding: 0 20px;
      }
    }
  }
}
</style>
